package com.photo.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.photo.system.annotation.AuthCheck;
import com.photo.system.common.BaseResponse;
import com.photo.system.common.DeleteRequest;
import com.photo.system.common.ErrorCode;
import com.photo.system.common.ResultUtils;
import com.photo.system.constant.UserConstant;
import com.photo.system.exception.BusinessException;
import com.photo.system.exception.ThrowUtils;
import com.photo.system.model.dto.Appointment.AppointmentAddRequest;
import com.photo.system.model.dto.Appointment.AppointmentQueryRequest;
import com.photo.system.model.dto.Appointment.AppointmentUpdateRequest;
import com.photo.system.model.dto.Appointment.AppointmentUpdateStatusRequest;
import com.photo.system.model.dto.categories.CategoriesUpdateRequest;
import com.photo.system.model.entity.Appointment;
import com.photo.system.model.entity.Categories;
import com.photo.system.model.entity.User;
import com.photo.system.model.vo.AppointmentVO;
import com.photo.system.model.vo.CategoriesVO;
import com.photo.system.model.vo.LoginUserVO;
import com.photo.system.service.AppointmentService;
import com.photo.system.service.CategoriesService;
import com.photo.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 预约摄影接口
 *
 * @author xuwenhui
 */
@RestController
@RequestMapping("/appointment")
@Slf4j
@Api(tags = {"预约摄影接口"})
public class AppointmentController {

    @Resource
    private AppointmentService appointmentService;

    @Resource
    private CategoriesService categoriesService;

    @Resource
    private UserService userService;

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    // region 增删改查

    /**
     * 创建预约摄影
     *
     * @param appointmentAddRequest
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "创建预约摄影")
    public BaseResponse<Long> addCategories(@RequestBody AppointmentAddRequest appointmentAddRequest, HttpServletRequest request) {
        if (appointmentAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        User user = userService.getLoginUser(request);
        QueryWrapper<Categories> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", appointmentAddRequest.getCategory());
        Categories one = categoriesService.getOne(queryWrapper);
        if (one == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "分类不存在");
        }
        Appointment appointment = new Appointment();
        BeanUtils.copyProperties(appointmentAddRequest, appointment);
        appointment.setUserId(user.getId());
        appointment.setCategoryId(one.getId());
        appointment.setStatus("待审核");
        boolean result = appointmentService.save(appointment);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建失败");
        return ResultUtils.success(appointment.getId());
    }

    /**
     * 删除预约摄影（仅管理员）
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "删除预约摄影（仅管理员）")
    public BaseResponse<Boolean> deleteCategories(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        boolean result = appointmentService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除失败");
        return ResultUtils.success(result);
    }

    /**
     * 更新预约摄影
     *
     * @param appointmentUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新预约摄影")
    public BaseResponse<Boolean> updateCategories(@RequestBody AppointmentUpdateRequest appointmentUpdateRequest, HttpServletRequest request) {
        if (appointmentUpdateRequest == null || appointmentUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }

        // 查询旧的预约信息
        QueryWrapper<Appointment> queryAppointment = new QueryWrapper<>();
        queryAppointment.eq("id", appointmentUpdateRequest.getId());
        Appointment oldAppointment = appointmentService.getOne(queryAppointment);

        // 获取分类信息
        QueryWrapper<Categories> queryCategories = new QueryWrapper<>();
        String categoryTitle = appointmentUpdateRequest.getCategory();
        if (categoryTitle == null || categoryTitle.isEmpty()) {
            Long categoryId = oldAppointment.getCategoryId();
            if (categoryId != null) {
                Categories category = categoriesService.getById(categoryId);
                if (category != null) {
                    categoryTitle = category.getTitle();
                }
            }
        }
        queryCategories.eq("title", categoryTitle);
        Categories category = categoriesService.getOne(queryCategories);

        if (category == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "更新的分类不存在");
        }

        if (appointmentUpdateRequest.getLocation() == null || appointmentUpdateRequest.getLocation().equals("")) {
            appointmentUpdateRequest.setLocation(oldAppointment.getLocation());
        }

        // 更新预约信息
        Appointment appointment = new Appointment();
        appointment.setCategoryId(category.getId());
        BeanUtils.copyProperties(appointmentUpdateRequest, appointment);
        boolean result = appointmentService.updateById(appointment);

        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新失败");
        }

        return ResultUtils.success(result);
    }

    /**
     * 管理员审核预约摄影
     *
     * @param appointmentQueryRequest
     * @return
     */
    @PostMapping("/change/status")
    @ApiOperation(value = "管理员审核预约摄影（仅管理员）")
    public BaseResponse<Boolean> changeStatus(@RequestBody AppointmentUpdateStatusRequest appointmentQueryRequest) {
        if (appointmentQueryRequest == null || appointmentQueryRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        Appointment appointment = new Appointment();

        BeanUtils.copyProperties(appointmentQueryRequest, appointment);

        boolean result = appointmentService.updateById(appointment);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新失败");
        return ResultUtils.success(result);
    }


    /**
     * 获取所有预约摄影（仅管理员）
     *
     * @param appointmentQueryRequest
     * @return
     */
    @PostMapping("/get/all")
    @ApiOperation(value = "获取所有预约摄影（仅管理员）")
    public BaseResponse<Page<AppointmentVO>> getAllCategories(@RequestBody AppointmentQueryRequest appointmentQueryRequest) {
        long current = appointmentQueryRequest.getCurrent() == 0 ? 1 : appointmentQueryRequest.getCurrent();
        long size = appointmentQueryRequest.getPageSize() == 0 ? 10 : appointmentQueryRequest.getPageSize();
        Page<AppointmentVO> pageParam = new Page<>(current, size);

        Page<AppointmentVO> gradeVOPage = appointmentService.getQueryWrapperByAll(pageParam, appointmentQueryRequest);
        return ResultUtils.success(gradeVOPage);
    }

    /**
     * 获取个人的预约摄影
     *
     * @param appointmentQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/get/my")
    @ApiOperation(value = "获取个人的预约摄影")
    public BaseResponse<Page<AppointmentVO>> getMyCategories(@RequestBody AppointmentQueryRequest appointmentQueryRequest,HttpServletRequest request) {
        long current = appointmentQueryRequest.getCurrent() == 0 ? 1 : appointmentQueryRequest.getCurrent();
        long size = appointmentQueryRequest.getPageSize() == 0 ? 10 : appointmentQueryRequest.getPageSize();
        User user = userService.getLoginUser(request);
        Long userId = user.getId();
        Page<AppointmentVO> pageParam = new Page<>(current, size);

        Page<AppointmentVO> gradeVOPage = appointmentService.getQueryWrapperByMy(pageParam, appointmentQueryRequest, userId);
        return ResultUtils.success(gradeVOPage);
    }

}
